/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Threading.Tasks;
using Oceanside.Payments.Credit;
using Oceanside.Payments;
using System.Linq;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    class VoiceAuthCommand : BindInterface
    {
        public VoiceAuthCommand(string name = "")
        {
            Text = name;
        }

        override public System.Windows.Visibility IsVisible
        {
            get
            {
                if (Constants.HasPaymentGateway && CloseCheck.StateObject.SelectedOrderNotNull && !CloseCheck.StateObject.CanCloseSelectedCheck)
                {
                    return System.Windows.Visibility.Visible;
                }
                else
                {
                    return System.Windows.Visibility.Hidden;
                }
            }
        }

        override public void Clicked()
        {
            try
            {
                if (Constants.IsTrainingMode)
                {
                    UMD.ShowGuiMessageSTASafe_NOTHROW("To protect cardholder data and remain PCI Compliant, credit card and gift card processing are not enabled while in training mode.");
                }
                else
                {
                    CreditCardEntryWindow ccew = new CreditCardEntryWindow(true);
                    ccew.ShowDialog();
                    if (CreditCardEntryWindow.HasCompleteInformation)
                    {
                        CreditCardGuiDataEnteredCallback(
                            CreditCardEntryWindow.Pan,
                            CreditCardEntryWindow.Expire,
                            CreditCardEntryWindow.VoiceAuthCode);
                    }
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
        }

        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        } 

        private static void CreditCardGuiDataEnteredCallback(string pan, string expire, string authcode)
        {
            try
            {
                App.CashMoneyWindowInstance.ShowMe();
                if (CashMoneyBox.LastResponse == UserResponse.ENTER && CashMoneyBox.TotalAmount != 0)
                {
                    MagneticCard magCard = new MagneticCard(pan, expire);
                    string response;

                    CACHE c = new CACHE();
                    ///I HAVE REMOVED THE ENCRPTION ALGORITHM TO PROTECT MY EXISTING CUSTOMERS FROM HACKS FROM MAKING THIS PUBLIC
                    ///KNOWLEDGE.  YOU MUST USE A STRONG ENCRYPTION ALGORITHM HERE AND NEVER STORE THE FULL MAG STRIPE EVER, NEVER.
                    //c.BinP = Crpt.ToBin(pan);
                    //c.BinE = Crpt.ToBin(expire);
                    c.BinP = GetBytes(pan);
                    c.BinE = GetBytes(expire);

                    c.DateTime = DateTime.Now;

                    SHIFT.GlobalContext.CACHES.AddObject(c);
                    SHIFT.GlobalContext.SaveChanges();

                    VoiceAuth data = new VoiceAuth();
                    data.InvoiceNo = SHIFT.SelectedOrder.Id.ToString();
                    data.Purchase = CashMoneyBox.TotalAmount.ToString("#0.00");
                    data.AuthCode = authcode;

                    ///Now send the request.
                    response = data.Request(magCard);

                    TRANSACTION_RESPONSE respMessage = new TRANSACTION_RESPONSE();
                    SHIFT.GlobalContext.TRANSACTION_RESPONSES.AddObject(respMessage);

                    ///This must be here so we generate a DB assigned ID to be used below.
                    SHIFT.GlobalContext.SaveChanges();

                    respMessage.Parse(response);

                    if (respMessage.CmdStatusOk)
                    {
                        TRANSACTION t = new TRANSACTION();
                        t.TerminalId = KIOSK.Get(SHIFT.GlobalContext).Id;
                        t.CustomerName = SHIFT.SelectedOrder.CustomerName;
                        t.BusinessDayId = BUSINESS_DAY.GetNow(SHIFT.GlobalContext).Id;
                        t.ExtId = c.Id;
                        t.Base = respMessage.AuthorizeDec;
                        t.OpenDateStamp = DateTime.Now;
                        t.LastModifiedDateStamp = DateTime.Now;
                        t.ORDER = SHIFT.SelectedOrder;
                        t.PaidAtRevenueCenterId = KIOSK.Get(SHIFT.GlobalContext).RevenueCenterId;
                        t.TransactionType = TRANSACTION.CONST_PAY_CREDIT;
                        t.TransactionTypeId = respMessage.Id;

                        if (SHIFT.SelectedOrder.HasHeadOfTable)
                        {
                            t.CustomerName = SHIFT.SelectedOrder.CustomerName;
                        }

                        t.OwningCheckNumber = CCBindings.SelectedSeatIndex;
                        t.UserId = SHIFT.Current.User.Id;
                        SHIFT.SelectedOrder.TRANSACTIONS.Add(t);
                        SHIFT.GlobalContext.SaveChanges();
                        CCBindings.RefreshThreadSafe(true);
                        CloseCheckWindow.StartChangeDueBlink();

                        if (KIOSK.HasLocalPrinter())
                        {
                            KIOSK k = KIOSK.Get(SHIFT.GlobalContext);
                            Int64 localPrinterId = (Int64)KIOSK.Get(SHIFT.GlobalContext).LocalPrinterId;

                            if (k.PrintCreditReceiptOnPay)
                            {
                                string localPrinterPath = SHIFT.GlobalContext.PRINTERS.Where(p => p.Id == localPrinterId).FirstOrDefault().Path;
                                CREDIT_TRANSACTION_PRINT_PACKET ctpp = new CREDIT_TRANSACTION_PRINT_PACKET();
                                ctpp.Transaction = t;
                                ctpp.TransactionResponse = respMessage;

                                for (int i = 0; i < k.NumberCreditReceipts; i++)
                                {
                                    PrintSpool.PrintCreditCardReceipt(localPrinterPath, SHIFT.SelectedOrder, ctpp, CCBindings.SelectedSeatIndex);
                                }
                            }

                            if (k.PrintItemizedReceiptOnPay)
                            {
                                ORDER order = SHIFT.SelectedOrder;
                                PrintSpool.PrintItemizedReceipt(
                                    localPrinterId,
                                    order,
                                    order.SelCheckAutoGratutiy,
                                    order.SelCheckRoundedSubtotal,
                                    order.SelCheckTax, CCBindings.SelectedSeatIndex);
                            }
                        }
                    }
                    else
                    {
                        UMD.ShowGuiMessageSTASafe_NOTHROW("The credit card transaction failed with a status of [" +
                            respMessage.TextResponse + "].");
                    }
                    SHIFT.GlobalContext.SaveChanges();
                }
            }
            catch (Exception e)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, e);
            }
        }
    }
}
